package cn.wolfcode.listener;

import cn.wolfcode.domain.MessageBoard;
import cn.wolfcode.redis.service.IRankRedisService;
import cn.wolfcode.service.IMessageBoardService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private IMessageBoardService messageBoardService;
    @Autowired
    private IRankRedisService rankRedisService;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        //从数据库中获取贴吧信息
        QueryWrapper<MessageBoard> wrapper = new QueryWrapper<>();
        wrapper.select("author_name authorName,count(author_name) count")
                .groupBy("author_name");
        List<Map<String, Object>> maps = messageBoardService.listMaps(wrapper);
        for (Map<String, Object> map : maps) {
            String authorName = (String)map.get("authorName");
            Long count = (Long)map.get("count");
            rankRedisService.initRankData(authorName,count);
        }
    }
}
